//
//  ViewController.m
//  11104B
//
//  Created by student on 16/3/1.
//  Copyright © 2016年 NIIT. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@property (nonatomic,strong) UIScrollView *scrollView;
@property (nonatomic,strong) UIView *moveView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    // 创建scrollView
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 22, 320, 50)];
    // 滑动条不显示
    self.scrollView.showsHorizontalScrollIndicator = NO;
    [self.view addSubview:self.scrollView];
    
    for (int i=0; i<10; i++) {
        UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(80*i, 0, 80, 50)];
        [btn setTitle:[NSString stringWithFormat:@"新闻%i",i+1] forState:UIControlStateNormal];
        // 按钮的正常状态颜色
        [btn setTitleColor:[UIColor greenColor] forState:UIControlStateNormal];
        // 选中过的颜色
        [btn setTitleColor:[UIColor redColor] forState:UIControlStateSelected];
        // 设置按钮的tag
        btn.tag = 100+i;
        // 设置初始默认选中第一个按钮
        if (btn.tag == 100)
        {
            btn.selected = YES;
        }
        // 添加按钮点击事件
        [btn addTarget:self action:@selector(btnPressed:) forControlEvents:UIControlEventTouchUpInside];
        // 添加按钮到scrollView上
        [self.scrollView addSubview:btn];
    }
    
    // 添加滑块
    UIView *moveView = [[UIView alloc] initWithFrame:CGRectMake(0,40,80,3)];
    moveView.backgroundColor = [UIColor redColor];
    [self.scrollView addSubview:moveView];
    self.moveView = moveView;
    
    // 设置滑动条的大小
    self.scrollView.contentSize = CGSizeMake(80*10, 50);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)btnPressed:(UIButton *)sender
{
    // 先将所有按钮取消选中状态
    for (UIView *v in self.scrollView.subviews)
    {
        if ([v isKindOfClass:[UIButton class]]) {
            UIButton *tmpBtn = v;
            tmpBtn.selected = NO;
        }
    }
    // 按钮触发的为选中状态
    sender.selected = YES;
    
    // 移动滑块
    // 滑块开始动画
    [UIView beginAnimations:nil context:nil];
    // 动画时间
    [UIView setAnimationDuration:0.1];
    int index = sender.tag - 100;
    self.moveView.frame = CGRectMake(80*index, 40, 80, 5);
    // 动画结束
    [UIView commitAnimations];
}

@end
